/*
 * @Author: DESKTOP-05FP536\Administrator 18368095041@163.com
 * @Date: 2025-01-15 17:16:36
 * @LastEditors: DESKTOP-05FP536\Administrator 18368095041@163.com
 * @LastEditTime: 2025-01-15 17:48:54
 * @FilePath: \road-admin-web\src\views\common\MyInfo\usePassword.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useMy, PasswordParam } from '@/service/useMy';
import { useRules } from '@/service/useRules';
import { FormInstance } from 'element-plus';
import { message } from '@/utils/message';

export class PasswordWithConfirmParam extends PasswordParam {
    confirmPassword = '';
}
export const usePassword = (formRef: Ref<FormInstance | undefined>) => {
    const passwordParam = ref(new PasswordWithConfirmParam());

    const { updateMyPassword, updatepasswordLoading } = useMy();

    const { requiredRule, passwordRule, compareRuleCreator } = useRules();

    const { newPassword } = toRefs(passwordParam.value);

    const passwordRules = {
        originPassword: [...requiredRule],
        newPassword: [...requiredRule, ...passwordRule],
        confirmPassword: [
            ...requiredRule,
            ...compareRuleCreator(newPassword, '新密码和确认密码不一致')
        ]
    };

    const handleSubmit = () => {
        formRef.value?.validate(async (isValid) => {
            if (isValid) {
                const { confirmPassword, ...rest } = passwordParam.value;
                await updateMyPassword(rest);
                message('操作成功', 'success');
            }
        });
    };

    const reset = () => {
        formRef.value?.resetFields();
        passwordParam.value = new PasswordWithConfirmParam();
    };

    return {
        passwordParam,
        updateMyPassword,
        updatepasswordLoading,
        handleSubmit,
        reset,
        passwordRules
    };
};
